package com.kxy.auth.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.kxy.auth.service.impl.MyUserDetailsService;
import com.kxy.auth.service.security.CustomAuthenticationProvider;
import com.kxy.auth.web.filter.JWTAuthenticationFilter;
import com.kxy.auth.web.filter.JWTLoginFilter;


//public class WebSecurityConfig{}
 
/**
 * SpringSecurity的配置
 * 通过SpringSecurity的配置，将JWTLoginFilter，JWTAuthenticationFilter组合在一起
 * @author zhaoxinguo on 2017/9/13.
 */
@Configuration
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
//	@Autowired
//    private MyUserDetailsService userDetailsService;
 
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    
    
   
 
    public WebSecurityConfig( BCryptPasswordEncoder bCryptPasswordEncoder) {
       // this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.cors().and().csrf().disable().authorizeRequests()
//                .antMatchers(HttpMethod.POST, "/security/login").permitAll()
//                .anyRequest().authenticated()
//                .and()
//                .addFilter(new JWTLoginFilter(authenticationManager()))
//                .addFilter(new JWTAuthenticationFilter(authenticationManager()));
    	
    	 // 关闭csrf验证
        http.csrf().disable()
                // 对请求进行认证
                .authorizeRequests()
                // 所有OPTIONS请求全部放行
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 所有 / 的所有请求 都放行
                .antMatchers("/").permitAll()
                // 所有 /login 的POST请求 都放行
                .antMatchers(HttpMethod.POST, "/security/login").permitAll()
                // 权限检查
              //  .antMatchers("/hello").hasAuthority("AUTH_WRITE")
                // 角色检查
             //   .antMatchers("/world").hasRole("ADMIN")
                // 对Rest请求需要身份认证, 放行OPTIONS
            .antMatchers(HttpMethod.POST).authenticated()
            .antMatchers(HttpMethod.PUT).authenticated()
            .antMatchers(HttpMethod.DELETE).authenticated()
            .antMatchers(HttpMethod.GET).authenticated()
                .and()
                // 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
                .addFilterBefore(new JWTLoginFilter("/security/login", authenticationManager()),
                        UsernamePasswordAuthenticationFilter.class)
                // 添加一个过滤器验证其他请求的Token是否合法
                .addFilterBefore(new JWTAuthenticationFilter(),
                        UsernamePasswordAuthenticationFilter.class);
    }
    
    
//    @Autowired
//	public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
//		// auth.inMemoryAuthentication()
//		// .withUser("user").password("password").roles("USER")
//		// .and()
//		// .withUser("app_client").password("nopass").roles("USER")
//		// .and()
//		// .withUser("admin").password("password").roles("ADMIN");
//		//配置用户来源于数据库
//		//auth.userDetailsService(userDetailsService());
//		auth.userDetailsService(myUserDetailsService);
//    }

    
    @Bean
    UserDetailsService customUserService(){
        return new MyUserDetailsService();
    }
 
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
    	auth.authenticationProvider(new CustomAuthenticationProvider());
      //  auth.userDetailsService(customUserService()).passwordEncoder(bCryptPasswordEncoder);
    }
    
//    @Bean
//    public DaoAuthenticationProvider authenticationProvider() {
//        DaoAuthenticationProvider authProvider
//          = new DaoAuthenticationProvider();
//        authProvider.setUserDetailsService(userDetailsService);
//        authProvider.setPasswordEncoder(bCryptPasswordEncoder);
//        return authProvider;
//    }
 
}